<template>
    <button
        v-if="!noStop"
        class="login-button"
        @click="onClick"
        :open-type="openType"
        @getphonenumber="getPhoneNumber"
        hover-class="none"
    >
        <slot></slot>
    </button>
    <button
        v-else
        class="login-button"
        @click.stop="onClick"
        :open-type="openType"
        @getphonenumber="getPhoneNumber"
        hover-class="none"
    >
        <slot></slot>
    </button>
</template>

<script setup>
/**
 * @description: 全局登录按钮组件
 * @author yinzhi
 * @date 2025-03-05
 */
import { computed } from 'vue'
import { useStore } from 'vuex'
import { throttle, debounce } from '@/uni_modules/uview-plus'
import { logger } from '@/utils/log.js'
import { loginApi } from '@/libs/api/baseApi.js'

// 定义 props
const props = defineProps({
    click: {
        type: Function,
        default: () => () => {}
    },
    // 是否需要冒泡阻止点击事件
    noStop: {
        type: Boolean,
        default: false
    },
    debounceTime: {
        type: Number,
        default: 0
    }
})
const emit = defineEmits()
// 获取 Vuex store
const store = useStore()

// 定义响应式数据
const token = computed(() => store.state.auth.token)
const wxCode = computed(() => store.state.auth.wxCode)

// 计算 openType
const openType = computed(() => (!token.value ? 'getPhoneNumber' : null))

// 点击事件
const onClick = () => {
    if (!openType.value) {
        throttle(() => emit('click'), props.debounceTime)
    }
}

// 获取手机号授权
const getPhoneNumber = async e => {
    debounce(() => phoneNumber(e), 300)
}

// 获取服务端接口电话号码
const phoneNumber = async e => {
    const { encryptedData } = e.detail
    if (!encryptedData) return
    await store.dispatch('auth/checkWxCode')
    await login(e)
}

// 用户登录
const login = async e => {
    uni.showLoading({
        mask: true,
        title: '登录中请稍后'
    })
    try {
        const { encryptedData, iv } = e.detail
        const params = {
            code: wxCode.value,
            encryptedData,
            iv
        }
        // 登录接口
        const { data } = {
            data: {
                token: 'token',
                userInfo: {
                    avatar: '', //头像
                    id: 1, //用户id
                    mobile: '15526450310', //手机号码
                    nickname: '微信用户' //用户名
                }
            }
        }
        // const { data } = await loginApi(params)
        const { token } = data
        await store.commit('auth/setToken', token)
        await store.commit('platform/setUserInfo', userInfo)
        // 关闭loading 提示登录成功
        uni.hideLoading()
        uni.showToast({
            title: '登录成功',
            icon: 'success',
            duration: 2000
        })
        // 触发初始化事件，或者说是等于后一些需要初始化的操作
        let time = setTimeout(() => {
            emit('init')
            time && clearTimeout(time)
        }, 1000)
    } catch (e) {
        logger.error({ '[login]-登录失败：': e })
        store.dispatch('auth/initWxCode')
        uni.hideLoading()
        uni.showToast({
            title: '登录失败，请重新登录',
            icon: 'none'
        })
    }
}
</script>

<style lang="scss" scoped>
.login-button {
    display: block;
    margin: 0;
    padding-left: 0;
    padding-right: 0;
    line-height: 1;
    margin-right: 0;
    margin-left: 0;
    border-radius: 0;
    overflow: initial;
    background-color: transparent;
}

button::after {
    display: none;
}
</style>
